<?php
namespace Engine;
class Dispatcher
{
    public static function run(\Application\Boot $app)
    {
        try {
            // Init vars
            $request = $app->getRequest();
            $response = $app->getResponse();
            $router = $app->getRouter();

            // match
            $route = $router->match($request);

            // if route empty then send response page not found
            if (empty($route)) {
                throw new \Exception('Route not found');
            }

            if (empty($route['path'])) {
                throw new \Exception('Action path is not set');
            }

            if (!is_file($route['path'])) {
                throw new \Exception('Action file is not found');
            }

            $view = $app->getView();
            
            if ($request->isAjax()) {
                $view->disableLayout();
            }
            // include action file
            include $route['path'];

            // run function action - main and get params for view
            $view_params = main($app);
            $view->assign($view_params);
            // set content
            if (isset($view_params['_options']['format']) 
                    && $view_params['_options']['format'] === 'json'
                    || strpos($request->serverParam('HTTP_ACCEPT'), 'json') !== false) {
                $content = $view_params;
                // set response type
                $response->setContentTypeJSON();
            } else {
                $content = (isset($view_params['_options']['script'])) 
                ? $view->renderScript($view_params['_options']['script'])
                : $view->renderScript($route['script_path']);                
                // set response type
                $response->setContentTypeHTML();
            }
            
            $body = $view->render($content);
            $status = (isset($view_params['_options']['response']['status'])) 
                ? $view_params['_options']['response']['status'] 
                : 200;
            $response->setStatus($status)->write($body)->sendResponse($request);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}